package com.web.base.open.provider;

import com.blue.core.tree.TreeBuilder;
import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.base.open.exception.OpenException;
import com.web.base.open.facade.UrlFacade;
import com.web.base.open.message.UrlRequest;
import com.web.base.open.message.UrlResponse;
import com.web.base.open.model.Url;
import com.web.base.open.service.UrlService;
import com.web.base.open.util.UrlConvertor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Component("openUrlProvider")
public class UrlProvider implements UrlFacade
{
	@Resource
	private UrlService urlService;
	
	public UrlProvider()
	{
	}

	@Override
	public UrlResponse add(UrlRequest request)
	{
		ValidationUtil.valid(request, SaveModel.class);
		Url url = UrlConvertor.toUrl(request);
		url = urlService.save(url);
		UrlResponse response = UrlConvertor.toResponse(url);
		return response;
	}

	@Override
	public UrlResponse update(UrlRequest request)
	{
		ValidationUtil.valid(request, UpdateModel.class);
		Url url = UrlConvertor.toUrl(request);
		url = urlService.save(url);
		UrlResponse response = UrlConvertor.toResponse(url);
		return response;
	}

	@Override
	public UrlResponse get(Integer id)
	{
		if (id == null)
			throw new OpenException("链接ID不能为空");
		
		Url url = urlService.get(id);
		UrlResponse response = UrlConvertor.toResponse(url);
		return response;
	}

	@Override
	public Map<String, List<UrlResponse>> listTree()
	{
		List<Url> list = urlService.list(null);
		List<UrlResponse> responseList = UrlConvertor.toResponse(list);
		Map<String, List<UrlResponse>> responseMap = TreeBuilder.buildMenu(responseList);
		return responseMap;
	}
	
}
